﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Water.Web.Controls.BaseInterface;

[assembly: WebResource("Water.Resources.Default.JS.GridView.Grid.js", "text/javascript")]
namespace Water.Web.Controls
{
    public partial class GridView : System.Web.UI.WebControls.GridView, IPageableItemContainer
    {

        public GridView()
            : base()
        {
            this.PagerSettings.Visible = false;
        }

        /// <summary>
        /// TotalRowCountAvailable event key
        /// </summary>
        private static readonly object EventTotalRowCountAvailable = new object();

        /// <summary>
        /// Call base control's CreateChildControls method and determine the number of rows in the source 
        /// then fire off the event with the derived data and then we return the original result.
        /// </summary>
        /// <param name="dataSource"></param>
        /// <param name="dataBinding"></param>
        /// <returns></returns>
        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
        {
            int rows = base.CreateChildControls(dataSource, dataBinding);

            //  if the paging feature is enabled, determine the total number of rows in the datasource
            if (this.AllowPaging)
            {
                //  if we are databinding, use the number of rows that were created, otherwise cast the datasource to an Collection and use that as the count
                int totalRowCount = dataBinding ? rows : ((ICollection)dataSource).Count;

                //  raise the row count available event
                IPageableItemContainer pageableItemContainer = this as IPageableItemContainer;
                this.OnTotalRowCountAvailable(new PageEventArgs(pageableItemContainer.StartRowIndex, pageableItemContainer.MaximumRows, totalRowCount));

                //  make sure the top and bottom pager rows are not visible
                if (this.TopPagerRow != null)
                    this.TopPagerRow.Visible = false;

                if (this.BottomPagerRow != null)
                    this.BottomPagerRow.Visible = false;
            }
            return rows;
        }

        #region IPageableItemContainer 成员
        /// <summary>
        /// Set the control with appropriate parameters and bind to right chunk of data.
        /// </summary>
        /// <param name="startRowIndex"></param>
        /// <param name="maximumRows"></param>
        /// <param name="databind"></param>
        void IPageableItemContainer.SetPageProperties(int startRowIndex, int maximumRows, bool databind)
        {
            int newPageIndex = (startRowIndex / maximumRows);
            this.PageSize = maximumRows;

            if (this.PageIndex != newPageIndex)
            {
                bool isCanceled = false;
                if (databind)
                {
                    //  create the event arguments and raise the event
                    GridViewPageEventArgs args = new GridViewPageEventArgs(newPageIndex);
                    this.OnPageIndexChanging(args);

                    isCanceled = args.Cancel;
                    newPageIndex = args.NewPageIndex;
                }

                //  if the event wasn't cancelled change the paging values
                if (!isCanceled)
                {
                    this.PageIndex = newPageIndex;

                    if (databind)
                        this.OnPageIndexChanged(EventArgs.Empty);
                }
                if (databind)
                    this.RequiresDataBinding = true;
            }
        }

        /// <summary>
        /// IPageableItemContainer's StartRowIndex = PageSize * PageIndex properties
        /// </summary>
        int IPageableItemContainer.StartRowIndex
        {
            get { return this.PageSize * this.PageIndex; }
        }

        /// <summary>
        /// IPageableItemContainer's MaximumRows  = PageSize property
        /// </summary>
        int IPageableItemContainer.MaximumRows
        {
            get { return this.PageSize; }
        }

        event EventHandler<PageEventArgs> IPageableItemContainer.TotalRowCountAvailable
        {
            add { base.Events.AddHandler(GridView.EventTotalRowCountAvailable, value); }
            remove { base.Events.RemoveHandler(GridView.EventTotalRowCountAvailable, value); }
        }
        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            PageManager.Register(this);
            //this.Page.ClientScript.RegisterClientScriptResource(typeof(GridView), "Water.Resources.Default.JS.GridView.Grid.js");
            PageManager.RegisterPageStyleSheet(this, "Grid_CSS", "CSS/Grid.css");
        }

        protected virtual void OnTotalRowCountAvailable(PageEventArgs e)
        {
            EventHandler<PageEventArgs> handler = (EventHandler<PageEventArgs>)base.Events[GridView.EventTotalRowCountAvailable];
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected override GridViewRow CreateRow(int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
        {
            GridViewRow row = base.CreateRow(rowIndex, dataSourceIndex, rowType, rowState);
            return row;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (this is IUpdatedableControl)
                Marker.WriteAJAXBegin(writer, this, false, RenderPackager);

            //writer.AddAttribute(HtmlTextWriterAttribute.Class, "default_g");
            //base.Render(writer);
            RenderCustom(writer);

            if (this is IUpdatedableControl)
                Marker.WriteAJAXEnd(writer, this);
            /*
            string js = @"$j('#__" + this.ClientID + "__').grid({fromTable:true});";
            js = @"$j(function() {" + js + "});";
            this.Page.ClientScript.RegisterStartupScript(typeof(GridView), this.UniqueID, js + "\n", true);
            */
        }
        /// <summary>
        /// 自定义Render 防止gridview默认输出 div仅仅让其输出 table
        /// </summary>
        /// <param name="writer"></param>
        private void RenderCustom(HtmlTextWriter writer)
        {
            if (null != this.Page)
                this.Page.VerifyRenderingInServerForm(this);
            this.PrepareControlHierarchy();
            this.RenderContents(writer);
        }
      
        protected override void OnRowCreated(GridViewRowEventArgs e)
        {
            base.OnRowCreated(e);
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.CssClass = "";
                int rowIndex = e.Row.RowIndex;
                string cssClass = "default_gac";
                int cellIndex=0;
                if (0 == rowIndex % 2)
                {
                    cssClass = "default_gc";
                    e.Row.CssClass = "default_g_rows";
                }
                else
                    e.Row.CssClass = "default_g_a_rows";
                foreach (TableCell cell in e.Row.Cells)
                {
                    cell.CssClass = cssClass;
                    cell.Attributes["axis"] = cellIndex.ToString();
                    cellIndex++;
                }

            }
            else if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.CssClass = "default_g_header";
                foreach (TableCell cell in e.Row.Cells)
                {
                    cell.CssClass = "default_ghc";
                    DataControlFieldCell d_cell = (DataControlFieldHeaderCell)cell;
                    DataControlField dcf = d_cell.ContainingField;
                    string width = dcf.HeaderStyle.Width.ToString();
                    if (!string.IsNullOrEmpty(width))
                    {
                        cell.Attributes["width"] = width;
                    }
                }
            }

        }


        private void RenderPackager(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "default_g");
        }


    }
}
